'use strict';

const moment = require('moment')
const { parse } = require('./profileParser.js')
const { sortDate } = require('./utils.js')
const db = uniCloud.database();

exports.main = async ({keywords = {}}) => {	
	const collection = db.collection('profiles')
	let {data: profiles} = await collection.get()
	// let profiles = res.data.map(raw => {return parse(raw)})
	
	for(let i=0;i<profiles.length;i++) {
		profiles[i] = await parse(profiles[i] )
	}
	
	
	if (keywords.availability && keywords.availability.availableDate) {
	    profiles = profiles.filter(profile => {
	        return moment(profile.availability.availableDate).isSameOrBefore(moment(keywords.availability.availableDate))
	    })
	}
	
	if (keywords.cost && keywords.cost.amount) {
	    const [min, max] = keywords.cost.amount
	    profiles = profiles.filter(profile => {
	        profile.cost.unit !== 'PerManHour'
	            ?
	            (profile.cost.unit !== 'PerManDay' ? profile.cost.amount = (profile.cost.amount) / 1000 : profile.cost.amount = (profile.cost.amount * 21.75) / 1000)
	            :
	            profile.cost.amount = (profile.cost.amount * 8 * 21.75) / 1000

	        return profile.cost.amount >= min
	            && profile.cost.amount <= max
	    })
	}
	
	if (keywords.profession && keywords.profession.experience) {
	    const [min, max] = keywords.profession.experience
		profiles = profiles.filter(profile => {
			return profile.profession.experience>=min && profile.profession.experience<=max
		})
	}
	
	if (keywords.education !== undefined && keywords.education.diploma !== undefined) {
	  const diplomas = keywords.education.diploma.length ? keywords.education.diploma : [keywords.education.diploma]
	  profiles = profiles.filter(profile => {
	   return diplomas.includes(profile.education.diploma)
	  })
	 }
	 
	if (keywords.profession && keywords.profession.tags)
	    profiles = profiles.filter(profile => {
	    const tags= keywords.profession.tags
	    const num = profile.profession.tags.reduce((num, tag) => {
			return tags.find(_tag => {
				return _tag == tag
			}) ? num + 1 : num
		}, 0)
	    return keywords.profession && keywords.profession.tags && keywords.profession.tags.length == num
	})

	
	profiles = profiles.filter(profile => {
	    return moment(profile.createdDate).isSameOrBefore(moment(), 'day');
	})
			
	profiles = profiles.filter((profile) => {
	    return profile.availability.availableDate
	}).sort(sortDate)
	console.log(profiles)
	return {
		date: moment().format('YYYY-MM-DD'),
		status: 'success',
		total: profiles.length,
		data: profiles
	}
};
